package com.iespring.config.shiro;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * shiro的SessionManager
 * 用来保证跨域下session一致的问题
 */
@Component
public class MarketSessionManager extends DefaultWebSessionManager {

    /**认证完之后，把SessionId作为响应结果响应给前端，前端发送请求通过请求头携带了sessionId*/
    private static final String MARKET_ADMIN_TOKEN="X-CskaoyanMarket-Admin-Token";
    /**小程序的SessionId的请求头*/
    private static final String MARKET_WX_TOKEN="X-CskaoyanMarket-Token";

    @Override
    protected Serializable getSessionId(ServletRequest servletRequest, ServletResponse response) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        request.setAttribute(ShiroHttpServletRequest.SESSION_ID_URL_REWRITING_ENABLED,this.isSessionIdUrlRewritingEnabled());
        //admin
        String adminSessionId = request.getHeader(MARKET_ADMIN_TOKEN);
        if(adminSessionId !=null && !"".equals(adminSessionId)){
            return adminSessionId;
        }
        //wx
        String wxSession = request.getHeader(MARKET_WX_TOKEN);
        if(wxSession !=null &&!"".equals(wxSession)){
            return wxSession;
        }
        return super.getSessionId(servletRequest, response);
    }
}
